package cn.py.boot_lua.processTa;

import cn.py.boot_lua.handler.admin.RequestTask;
import cn.py.boot_lua.handler.generic.GenericQueueService;
import cn.py.boot_lua.handler.generic.QueueType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.Semaphore;

@Slf4j
@Component
public class ScheduledProcess {

    private final GenericQueueService genericQueueService;
    private final StrategyFactory strategyFactory;
    private final TaskSemaphoreManager semaphoreManager;

    public ScheduledProcess(GenericQueueService genericQueueService,
                            StrategyFactory strategyFactory,
                            TaskSemaphoreManager semaphoreManager) {
        this.genericQueueService = genericQueueService;
        this.strategyFactory = strategyFactory;
        this.semaphoreManager = semaphoreManager;
    }

    /**
     *  执行方法
     */
    @Scheduled(fixedRate = 1000)
    public void process() {
        for (QueueType queueType : QueueType.values()) {
            TaskProcessStrategy strategy = strategyFactory.getStrategy(queueType);  //需要执行的方法
            if (strategy != null) {
                RequestTask task = genericQueueService.pollFromQueue(queueType.getKey()); //获取队列任务
                if (task != null) {
                    Semaphore semaphore = semaphoreManager.getSemaphore(queueType); //获取并发
                    strategy.process(task, semaphore, genericQueueService);
                }
            }
        }
    }

}
